package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.RecommendUser;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.db.Visitor;
import com.itheima.service.db.*;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsk
 * @create 2022-03-20-15:46
 */
@Component
public class MakeFriendManager {

    @DubboReference
    private RecommendUserService recommendUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private VisitorService visitorService;

    @DubboReference
    private UserLocationService userLocationService;

    @DubboReference
    private QuestionService questionService;

    //查询今日佳人
    public ResponseEntity findTodayBest() {

        //获取线程内UserId
        Long toUserId = UserHolder.get().getId();

        //根据userId查询今日佳人
        RecommendUser recommendUser = recommendUserService.findTodayBest(toUserId);

        //封装RecommendUserVo对象
        RecommendUserVo vo = new RecommendUserVo();

        //先查询后封装userInfo
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());//大数据推荐的用户id

        vo.setUserInfo(userInfo);

        //后封装缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        //返回vo
        return ResponseEntity.ok(vo);

    }

    //推荐朋友
    public ResponseEntity findRecommendUserVoByPage(Integer pageNum, Integer pageSize) {

        //获取线程内toUserId
        Long toUserId = UserHolder.get().getId();

        //调用rpc查询推荐用户分页
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserVoByPage(toUserId,pageNum,pageSize);

        //封装voList集合对象
        List<RecommendUserVo> voList = new ArrayList<>();

        //获取当前页对象
        List<RecommendUser> recommendUserList = (List<RecommendUser>) pageBeanVo.getItems();

        //非空判断
        if (CollectionUtil.isNotEmpty(recommendUserList)){
            for (RecommendUser recommendUser : recommendUserList) {
                RecommendUserVo vo = new RecommendUserVo();

                //先查询userInfo后封装
                UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());//被推荐人id
                vo.setUserInfo(userInfo);

                //存储推荐值
                vo.setFateValue(recommendUser.getScore().longValue());

                //最后存储到集合对象中
                voList.add(vo);
            }
        }

        //存储到分页对象中
        pageBeanVo.setItems(voList);

        //返回前端结果
        return ResponseEntity.ok(pageBeanVo);

    }

    //推荐用户详情
    public ResponseEntity findPersonalInfo(Long jiarenId) {

        //获取线程内toUserId
        Long toUserId = UserHolder.get().getId();

        //调用rpc查询缘分值对象
        RecommendUser recommendUser = recommendUserService.findPersonalInfo(toUserId,jiarenId);

        //解决自己、好友查不到推荐用户问题判断
        if (recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(jiarenId);//推荐人写传递过来的
            recommendUser.setScore(100d);//推荐值写满或者不写
        }

        //封装vo对象
        RecommendUserVo vo = new RecommendUserVo();

        //先查询UserInfo对象然后添加
        UserInfo userInfo = userInfoService.findById(jiarenId);//推荐佳人id

        vo.setUserInfo(userInfo);

        //封装缘分值
        vo.setFateValue(recommendUser.getScore().longValue());

        //返回vo对象
        return ResponseEntity.ok(vo);


    }

    //查询访客记录
    public ResponseEntity findVisitors() {

        //获取线程内UserId
        Long userId = UserHolder.get().getId();

        //获取redis的上次查询时间
        String lastAccessTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);

        List<VisitorVo> voList = new ArrayList<>();

        //判断Redis中有无记录
        if (StrUtil.isNotEmpty(lastAccessTime)){
            //查询访客信息
            List<Visitor> visitorList = visitorService.findVisitors(userId,Long.parseLong(lastAccessTime));
            if (CollectionUtil.isNotEmpty(visitorList)){
                for (Visitor visitor : visitorList) {

                    VisitorVo vo = new VisitorVo();

                    //先查询UserInfo对象然后封装
                    UserInfo userInfo = userInfoService.findById(visitor.getVisitorUserId());//访客id

                    vo.setUserInfo(userInfo);
                    //后封装缘分值
                    vo.setFateValue(visitor.getScore().longValue());

                    //封装到集合对象中
                    voList.add(vo);
                }
            }
        }

        //保存Redis的本次查询时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME +userId,
                String.valueOf(System.currentTimeMillis()));//这次登陆时间

        //返回voList
        return ResponseEntity.ok(voList);

    }

    //上报地理位置
    public void saveLocation(Double longitude, Double latitude, String addrStr) {
        //获取线程内userId
        Long userId = UserHolder.get().getId();

        //调用rpc保存
        userLocationService.saveLocation(longitude,latitude,addrStr,userId);
    }

    //搜索附近
    public ResponseEntity searchNearUser(String gender, Long distance) {

        //获取线程内UserId
        Long userId = UserHolder.get().getId();

        //调用rpc查看附近人id集合
        List<Long> nearUserIdList = userLocationService.searchNearUser(userId, distance);

        List<NearUserVo> voList = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(nearUserIdList)){
            for (Long nearUserId : nearUserIdList) {
                //排除自己
                if (userId == nearUserId){
                    continue;//结束本次循环
                }
                //先根据id查询附近人信息
                UserInfo userInfo = userInfoService.findById(nearUserId);

                //排除异性
                if (!StrUtil.equals(gender,userInfo.getGender())){
                    continue;
                }
                //封装NearUserVo对象
                NearUserVo vo = new NearUserVo();
                vo.setUserId(userInfo.getId());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());

                //封装到集合中
                voList.add(vo);
            }
        }

        //返回voList
        return ResponseEntity.ok(voList);

    }

    //聊一下查询陌生人问题
    public ResponseEntity strangerQuestions(Long jiarenId) {

        //调用rpc查询陌生人问题，根据jiarenId
        Question question = questionService.findByUserId(jiarenId);

        //判断非空
        if (question == null){
            question = new Question();
        }
        //返回结果
        return ResponseEntity.ok(question.getStrangerQuestion());//返回问题

    }
}
